import re

import xlrd as xlrd
from docx import Document
from docx.shared import Pt
from docx.oxml.ns import qn
import json
import requests

def send_get_request(url, params=None, headers=None):
    try:
        response = requests.get(url, params=params, headers=headers, timeout=1000)
        response.raise_for_status()  # 检查请求是否成功

        # 将响应内容解析为JSON（如果返回的是JSON格式）
        try:
            response_data = response.json()  # 解析为字典
            print("响应内容（JSON解析后）：")
            print(response_data)

            # 访问JSON中的特定字段（根据你的实际需求调整）
            if 'c2sActionClient' in response_data and 'requestParameterList' in response_data['c2sActionClient']:
                response_parameters = response_data['c2sActionClient']['requestParameterList']
                # protocolNo、name
                response_name = response_data['c2sActionClient']['name']
                protocolNo = response_data['c2sActionClient']['protocolNo']
                print(f"成功获取到{response_name}")
                print(f"成功获取到{len(response_parameters)}个响应参数")
                return response_parameters,response_name,protocolNo
            else:
                print("响应中不包含c2sActionClient或requestParameterList字段")
                return []

        except ValueError:
            print("响应内容不是有效的JSON格式")
            print("原始响应内容：")
            print(response.text)  # 打印原始文本内容
            return []

    except requests.exceptions.RequestException as e:
        print(f"请求出错：{e}")
        return []


def set_font(element, font_name='微软雅黑', font_size=10):
    """设置中文字体"""
    # 如果是段落对象
    if hasattr(element, 'runs'):
        if element.runs:
            run = element.runs[0]
        else:
            run = element.add_run()
    # 如果是表格单元格
    elif hasattr(element, 'paragraphs'):
        if element.paragraphs:
            paragraph = element.paragraphs[0]
            if paragraph.runs:
                run = paragraph.runs[0]
            else:
                run = paragraph.add_run()
        else:
            paragraph = element.add_paragraph()
            run = paragraph.add_run()
    else:
        return

    run.font.size = Pt(font_size)
    run.font.name = font_name
    run._element.rPr.rFonts.set(qn('w:eastAsia'), font_name)

def add_parameter_table(doc, parameters, parent_name=None, level=1, processed_parents=None):
    """
    递归添加参数表格
    :param doc: Word文档对象
    :param parameters: 参数列表
    :param parent_name: 父级参数名（用于表格标题）
    :param level: 当前层级（用于标题级别）
    """
    if processed_parents is None:
        processed_parents = set()

    # 如果parent_name已处理过，则跳过整个表格生成
    if parent_name and parent_name in processed_parents:
        return

    # 记录已处理的parent_name
    if parent_name:
        processed_parents.add(parent_name)
        # 添加父级标题
        heading = doc.add_paragraph(f'参数组: {parent_name}')
        heading.style = f'Heading {min(level + 1, 6)}'  # 限制最大标题级别为6
        set_font(heading, font_size=12)

    # 创建表格
    table = doc.add_table(rows=1, cols=5)
    table.style = 'Table Grid'

    # 设置表头
    hdr_cells = table.rows[0].cells
    headers = ['变量名', '字段描述', '类型', '预期/断言/Mock', '是否必须']
    for i, header in enumerate(headers):
        hdr_cells[i].text = header
        set_font(hdr_cells[i], font_size=10)

    # 添加数据行
    for param in parameters:
        # 检查identifier是否为serialVersionUID
        if param.get('identifier', '') == "serialVersionUID":
            continue  # 跳过这个参数，不生成行
        row_cells = table.add_row().cells
        row_data = [
            param.get('identifier', ''),
            param.get('name', ''),
            param.get('dataType', ''),
            param.get('remark', ''),
            param.get('must', '')
        ]

        for i, text in enumerate(row_data):
            row_cells[i].text = text
            set_font(row_cells[i], font_size=9)

        # 递归处理子参数
        if 'parameterList' in param and param['parameterList']:
            dataType = param.get('dataType', '')
            if dataType and "List<" in dataType:
                # 提取List中的实际类型名称
                match = re.search(r'List<(.*?)>', dataType)
                if match:
                    identifier = match.group(1)
                else:
                    identifier = param.get('dataType', '')
            else:
                identifier = param.get('dataType', '')

            add_parameter_table(doc, param['parameterList'],
                                identifier,
                                level + 1,
                                processed_parents)


def main(response_params,response_name,protocolNo):
    # 创建Word文档
    doc = Document()

    # 添加主标题
    title = doc.add_paragraph(protocolNo + response_name + '请求参数文档')
    title.alignment = 1  # 居中
    title.style = 'Title'
    set_font(title, font_size=16)

    # 添加空行
    # doc.add_paragraph()

    # 处理顶层参数
    for param in response_params:
        # 添加顶层标题
        top_heading = doc.add_paragraph(f'顶层参数: {param.get("name", "")}')
        top_heading.style = 'Heading 1'
        set_font(top_heading, font_size=14)

        # 处理参数列表
        if 'parameterList' in param and param['parameterList']:
            add_parameter_table(doc, param['parameterList'])
        else:
            doc.add_paragraph('无参数', style='Intense Quote')

    # 保存文档
    doc.save("./umeapi/new/" +response_name + '_请求参数.docx')
    print("Word文档已生成: " + response_name + '191.docx')

def api_data_handler(file_name):
    """接口Excel数据加载"""
    xlsx_book = xlrd.open_workbook(file_name)
    xlsx_sheet = xlsx_book.sheet_by_index(0)
    nrows = xlsx_sheet.nrows
    api_url_list = []
    for i in range(1, nrows):
        row_values = xlsx_sheet.row_values(i)
        # api_name = row_values[0]
        # url = row_values[1]
        # version = row_values[2]
        api_url = row_values[6]
        api_url_list.append(api_url)
    return api_url_list

if __name__ == "__main__":
    url_list = [
        "https://newtab@umedevops.local.umetrip.com/api/umeapiplus/action/getInterfaceDetailsNewNew?corporationId=6&projectName=umeapp-ticketorder&moduleId=0&pageId=0&actionId=2818780",
        "https://newtab@umedevops.local.umetrip.com/api/umeapiplus/action/getInterfaceDetailsNewNew?corporationId=0&projectName=umeapp-ticketorder&moduleId=0&pageId=0&actionId=2818783",
        "https://newtab@umedevops.local.umetrip.com/api/umeapiplus/action/getInterfaceDetailsNewNew?corporationId=6&projectName=umeapp-ticketorder&moduleId=0&pageId=0&actionId=2818675",
        "https://newtab@umedevops.local.umetrip.com/api/umeapiplus/action/getInterfaceDetailsNewNew?corporationId=6&projectName=umeapp-ticketorder&moduleId=0&pageId=0&actionId=2818759",
        "https://newtab@umedevops.local.umetrip.com/api/umeapiplus/action/getInterfaceDetailsNewNew?corporationId=0&projectName=umeapp-ticketorder&moduleId=0&pageId=0&actionId=2818756",
        "https://newtab@umedevops.local.umetrip.com/api/umeapiplus/action/getInterfaceDetailsNewNew?corporationId=6&projectName=umeapp-ticketorder&moduleId=0&pageId=0&actionId=2818750",
        "https://newtab@umedevops.local.umetrip.com/api/umeapiplus/action/getInterfaceDetailsNewNew?corporationId=6&projectName=umeapp-ticketorder&moduleId=0&pageId=0&actionId=2818681",
        "https://newtab@umedevops.local.umetrip.com/api/umeapiplus/action/getInterfaceDetailsNewNew?corporationId=0&projectName=umeapp-ticketorder&moduleId=0&pageId=0&actionId=2818684",
        "https://newtab@umedevops.local.umetrip.com/api/umeapiplus/action/getInterfaceDetailsNewNew?corporationId=0&projectName=umeapp-ticketorder&moduleId=0&pageId=0&actionId=2818687"]
    for url in url_list:
        response, response_name, protocolNo = send_get_request(url)
        if response is None:
            print(f"跳过URL: {url}")
            continue
        else:
            main(response, response_name, protocolNo)